package com.xiaoyang.forum.controller;

import cn.hutool.core.util.StrUtil;
import com.xiaoyang.forum.common.code.BaseController;
import com.xiaoyang.forum.common.code.Result;
import com.xiaoyang.forum.common.code.ResultCode;
import com.xiaoyang.forum.common.domain.OSSResult;
import com.xiaoyang.forum.common.util.JWTUtil;
import com.xiaoyang.forum.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController extends BaseController {

    @Autowired
    private IFileService FileService;

    /**
     * 上传文件
     * @param file
     * @param token
     * @return
     */
    @PostMapping("/upload")
    public Result<OSSResult> upload(@RequestBody MultipartFile file, @RequestHeader String token) {
        if (StrUtil.isEmpty(token)) {
            return Result.failed(ResultCode.USER_NO_LOGIN);
        }
        long userId = (long) JWTUtil.getUserIdFromToken(token); // 用户id
        return Result.success(FileService.upload(file, userId));
    }
}